# @Version        : 1.0
# @Update Time    : 2025/8/22 20:09
# @File           : log_service.py
# @IDE            : PyCharm
# @Desc           : 文件描述信息

from fastapi import Request
from user_agents import parse

from applications.core.context_manager.track_utils import TrackContextUtils
from applications.models import LoginLog
from applications.utils.xdb_searcher import XdbSearcher


async def login_log(request: Request, uid: int | None, form_data: str, is_access: int, remark: str = ""):
    """
    记录用户登录日志。

    :param remark:
    :param form_data:
    :param request: FastAPI 请求对象。
    :param uid: 用户 ID。
    :param is_access: 是否成功登录（True 或 False）。
    :return: 返回日志记录的 ID。
    """
    user_agent = parse(request.headers.get("user-agent", ""))
    ip = get_ip_address(request)
    # ip地址解析。
    with XdbSearcher() as xdb_searcher:
        ip_region = xdb_searcher.search_region(ip)
    log = LoginLog(
        url=request.url.path,
        ip=ip,
        request_id=TrackContextUtils.get_request_id(),
        user_id=uid,
        form=form_data,
        status=is_access,
        browser=f"{user_agent.browser.family} {user_agent.browser.version_string}",
        system=f"{user_agent.os.family} {user_agent.os.version_string}",
        country=ip_region.country,
        city=ip_region.city,
        province=ip_region.province,
        isp=ip_region.isp,
        remark=remark,
    )
    await log.save()
    return log.id


def get_ip_address(request: Request) -> str:
    """获取请求的IP地址

    Args:
        request: FastAPI请求对象

    Returns:
        str: IP地址
    """
    x_forwarded_for = request.headers.get("x-forwarded-for", "")
    if x_forwarded_for:
        return x_forwarded_for.split(",")[0].strip()

    x_real_ip = request.headers.get("X-Real-Ip", "")
    if x_real_ip:
        return x_real_ip

    return request.client.host
